<?php

declare(strict_types=1);

namespace app\admin\service\auth;

use app\common\model\auth\AdminModel;
use app\common\model\auth\AdminRoleModel;
use app\common\model\auth\RoleModel;
use app\common\model\auth\RolePermissionModel;
use app\common\model\PermissionModel;
use app\common\model\platform\AdminTenantModel;
use Dengje\Pxy\BaseService;
use dengje\jwt\facade\JWTAuth;
use think\facade\Db;

class AdminService extends BaseService
{
    protected $model = null;


    public function __construct()
    {

        $this->model = new \app\common\model\auth\AdminModel();

    }

    public function list()
    {
        $where = [];
        $realname = request()->get('realname');
        if ($realname)
            $where[] = ['realname', '=', $realname];
        $account = request()->get('account');
        if ($account)
            $where[] = ['account', '=', $account];

        $list = $this->model->where($where)->order(['id' => 'desc'])->paginate(request()->get('page_size/d', 10))->each(function ($item) {
            $roleIds = AdminRoleModel::where('admin_id', $item->id)->column('role_id');
            $role = RoleModel::whereIn('id', $roleIds)->field("name")->select();
            $item->role = $role;
        });
        return $list;
    }

    public function create($data)
    {
        // 判断是否有这个账号account
        $admin = $this->model->where('account', $data['account'])->findOrEmpty();
        if (!$admin->isEmpty()) {
            throw new \Exception('账号已存在');
        }

        // 如果有password就修改密码
        if (isset($data['password']) && $data['password'] != '') {
            $salt = rand(1000, 9999);
            $data['salt'] = $salt;
            $data['password'] = encrypt_password($data['password'], $salt);
        }
        $admin = $this->model->create($data);
        AdminRoleModel::updateRel($admin->id, $data['role_ids']);
        return $admin;
    }

    public function update($id, $data)
    {
        $data = $this->preExcludeFields($data);
        if (isset($data['role_ids'])) {
            AdminRoleModel::updateRel($id, $data['role_ids']);
            unset($data['role_ids']);
        }

        // 如果有password就修改密码
        if (isset($data['password']) && $data['password'] != '') {
            $salt = rand(1000, 9999);
            $data['salt'] = $salt;
            $data['password'] = encrypt_password($data['password'], $salt);
        }
        return $this->model->where('id', $id)->update($data);
    }

    public function detail($id)
    {
        $detail = $this->model->where('id', $id)->field('id,account,realname,status,is_super,create_time,update_time')->find();
        $detail->role_ids = AdminRoleModel::where('admin_id', $id)->column('role_id');
        return $detail;
    }

    public function delete($id)
    {
        Db::startTrans();
        try {

            AdminRoleModel::where('admin_id', $id)->delete();
            $this->model->where('id', $id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }


    public function updatePassword($adminId, $data)
    {
        if (isset($data['password']) && $data['password'] != '') {
            $salt = rand(1000, 9999);
            $data['salt'] = $salt;
            $data['password'] = encrypt_password($data['password'], $salt);
        }
        unset($data['old_password']);
        unset($data['confirm_password']);
        return $this->model->where('id', $adminId)->update($data);
    }


    /**
     * 获取用户权限标识
     */
    public function getAuthRuleList($adminId)
    {
        // $admin = $this->model->where('id',$adminId)->find();
        $roleIds = AdminRoleModel::where('admin_id', $adminId)->column('role_id');
        // $permissionIds = RolePermissionModel::whereIn('role_id',$roleIds)->column('permission_id');
        $rules = [];//PermissionModel::whereIn('id',$permissionIds)->where('permission_type',2)->column('permission_mark');

        return $rules;
    }


    /**
     * 检查用户是否有权限访问API
     */
    public static function checkApiAuth()
    {
        $adminId = request()->admin_id;
        $admin = AdminModel::find($adminId);
        // 超管放行
        if ($admin->is_super == 1 || in_array(request()->baseUrl(), ['/admin/passport/profile', '/admin/cloud/check'])) {
            return true;
        }
        $url = substr_replace(request()->baseUrl(), '', 0, 1);
        if(in_array($url,self::getCodes())){
            $codes = self::getCodes($adminId);
            // var_dump($codes);
            if (in_array($url, $codes)) {
                return true;
            }
            throw new \Exception('无权限访问', 403);
        }
        

    }

    public static function getCodes($adminId = null)
    {
        if($adminId){
            $roleIds = AdminRoleModel::where('admin_id', $adminId)->column('role_id');
            $codes = RolePermissionModel::whereIn('role_id', $roleIds)->column('code');
        }else{
            $codes = (new PermissionService())->getAllCode();
        }
       
        foreach ($codes as $key => $value) {
            if ($value) {
                $string = $value;
                $pattern = '/^\//'; // 正则表达式，匹配开头的斜杠
                $replacement = ''; // 替换为空字符串
                $codes[$key] = preg_replace($pattern, $replacement, $string);
            }
        }
        return $codes;
    }



}